import { Input } from 'antd';
import type { LngLatLike } from 'mapbox-gl';
import { useEffect, useRef, useState } from 'react';
import MapboxMarker, {
  type MapboxMarkerRef,
} from '@/components/MapView/components/MapboxMarker/Index';
import type { Mapless } from '@/components/MapView/Mapless';
import { attachOldStation } from '@/components/MapView/Mapless';
import StationModulePanel from '@/components/StationPanel/StationModulePanel';
import useStationData from '@/hooks/useStationData';
import type { Station } from '@/types/common';
import { StationList2MapStationList } from '../utils';
import styles from './index.module.less';

const MarkerInfo: React.FC<{
  isMapReady: boolean;
  mapless: Mapless | undefined;
}> = ({ isMapReady, mapless }) => {
  const { stationData: data } = useStationData();

  const markerRef = useRef<MapboxMarkerRef>(undefined);
  const maplessRef = useRef<Mapless>(undefined);

  useEffect(() => {
    if (isMapReady && mapless) {
      const sman = attachOldStation(mapless, 'sm1');
      sman?.drawStations(StationList2MapStationList(data || []));
      sman?.on('stationsSelected', (e) => {
        const sts = e.stations;
        const first = sts?.[0] || null;
        if (first) {
          const find = (data || []).find((item) => item.id === first.id);
          setSelectedStation(find);
          if (find) {
            const lnglat = [
              Number(find.longitude),
              Number(find.latitude),
            ] as LngLatLike;
            setPosition(lnglat);

            markerRef?.current?.show();
          }
        }
      });
      maplessRef.current = mapless;
    }
  }, [isMapReady, mapless, data]);

  const [position, setPosition] = useState<LngLatLike | undefined>();
  const [selectedStation, setSelectedStation] = useState<Station | undefined>();

  return (
    <MapboxMarker
      ref={markerRef}
      maplessRef={maplessRef}
      className={styles.marker}
      anchor="bottom"
      offsetY={-20}
      lngLat={position as LngLatLike}
    >
      <StationModulePanel
        modules={selectedStation?.driverModules || []}
        stationName={selectedStation?.name}
        stationState={selectedStation?.state}
      />
      test marker dom event
      <Input />
    </MapboxMarker>
  );
};

export default MarkerInfo;
